package com.wingtech.mqtt.controller;

import com.wingtech.mqtt.client.MqttPushClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;

/**
 * @author haungfeilong@wingtech.com
 * @version 1.0
 * @ClassName TestController
 * @description
 * @date 2020/11/26 18:35
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/mqtt")
@Slf4j
public class TestController {
    @Autowired
    private MqttPushClient mqttPushClient;

    @GetMapping(value = "/publishTopic")
    public String publishTopic() {
        String topicString = "testTopic";
        mqttPushClient.publish(0, false, topicString, "测试一下发布消息");
        return "ok";
    }
    // 发送自定义消息内容（使用默认主题）
    @RequestMapping("/publishTopic/{data}")
    public String test1(@PathVariable("data") String data) {
        String topicString = "testTopic";
        mqttPushClient.publish(0,false,topicString, data);
        return "ok";
    }

    // 发送自定义消息内容，且指定主题
    @GetMapping("/publishTopic2")
    public String test2(@PathParam("topic") String topic, @PathParam("data") String data) {
        mqttPushClient.publish(0,false,topic, data);
        return "ok";
    }

    @RequestMapping("/connectMqtt")
    public String connectMqtt(@PathParam("host") String host, @PathParam("clientID")String clientID, @PathParam("username")String username, @PathParam("password")String password, @PathParam("timeout")int timeout, @PathParam("keepalive")int keepalive){
        mqttPushClient.connect(host,clientID,username,password,timeout,keepalive);
        log.info("clientId:{}",mqttPushClient.getClient().getClientId());
        return "ok";
    }

    @RequestMapping("/subscribeTopic")
    public String subscribeTopic(String topic){
        mqttPushClient.subscribe(topic,0);
        log.info("clientId:{}",mqttPushClient.getClient().getClientId());
        return "ok";
    }
}
